<script setup>
import { onMounted, ref, computed, getCurrentInstance } from "vue";
import Hls from "hls.js";
import Process from "./Process.vue";
let currentInstance = "";

onMounted(() => {
  currentInstance = getCurrentInstance();
});

const offsetSecond = ref(120);
const startName = "lhs_offset_unix_s_0";
const url = ref(
  "https://domhttp.kksmg.com/2021/05/13/h264_450k_mp4_120c4170cd76e55062f73576cf12fc6e_ncm.mp4/playlist_av.m3u8"
);
let nowTimestamp = Date.now();
const startTimestamp = ref(nowTimestamp - offsetSecond.value * 1000);

let hlsPlayer = null;

const fullUrl = computed({
  get() {
    return `${url.value}?${startName}=${offsetSecond.value}`;
  },
});

const processComp = ref(null)

const initPlayer = () => {
  // processComp.value.start();
  console.log("🚀 ~ file: HlsTest.vue:31 ~ initPlayer ~ processComp.value", processComp.value)
};

const playVideo = () => {
  var videoSrc = fullUrl.value;
  var video = document.getElementById("video");
  if (Hls.isSupported()) {
    var hls = new Hls();
    // hls.js和video绑定
    hls.attachMedia(video);
    // 监听媒体资源准备就绪事件
    hls.on(Hls.Events.MEDIA_ATTACHED, function () {
      console.log("视频准备就绪");
      // 加载资源
      hls.loadSource(videoSrc);
      hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
        console.log(
          "manifest loaded, found " + data.levels.length + " quality level"
        );
        // 播放视频
        video.play();
      });
    });
    hlsPlayer = ref(hls);
  } else if (video.canPlayType("application/vnd.apple.mpegurl")) {
    video.src = videoSrc;
  }
};

const destroyVideo = () => {
  if (hlsPlayer && hlsPlayer.value) {
    hlsPlayer.value.destroy();
  }
};

const handleChangeStartTimestamp = (offset) => {
  offsetSecond.value = destroyVideo();
  playVideo();
};
</script>

<template>
  <div class="box">
    <div class="video-box">
      <video id="video"></video>
      <div class="process">
        <Process
          ref="processComp"
          :startTimestamp="startTimestamp"
          @getOffsetTimeSecond="handleChangeStartTimestamp"
        />
      </div>
    </div>
    <div class="input-wrap">地址：<input type="text" v-model="url" /></div>
    <br />
    <div class="input-wrap"><input type="text" v-model="fullUrl" /></div>
    <div class="tool-wrap">
      <button @click="initPlayer">初始化</button>
      <button @click="playVideo">播放</button>
      <button @click="destroyVideo">销毁</button>
    </div>
  </div>
</template>

<style scoped>
.input-wrap {
  margin-top: 20px;
  height: 30px;
}
.input-wrap input {
  padding: 0 10px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.tool-wrap {
  margin-top: 20px;
}
.video-box {
  position: relative;
  width: 800px;
  height: 500px;
  background: #000;
}
#video {
  width: 100%;
  height: 100%;
}

/* 进度条 */
.process {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  z-index: 1000;
}
</style>
